<template>
    <div class="verification-container">
        <h2>入群验证设置</h2>

        <el-card class="settings-card">
            <template #header>
                <div class="card-header">
                    <span>群组选择</span>
                </div>
            </template>

            <div class="group-select">
                <el-select v-model="selectedGroupId" placeholder="请选择群组" @change="handleGroupChange"
                    class="group-selector">
                    <el-option v-for="group in groupList" :key="group.groupId"
                        :label="group.name || `群组_${group.groupId}`" :value="group.groupId" />
                </el-select>
            </div>
        </el-card>

        <div v-if="selectedGroupId" class="settings-section">
            <el-card class="settings-card">
                <template #header>
                    <div class="card-header">
                        <span>验证设置</span>
                    </div>
                </template>

                <el-form :model="form" label-width="160px" :disabled="loading">
                    <el-form-item label="启用入群验证">
                        <el-switch v-model="form.enabled" />
                    </el-form-item>

                    <el-form-item label="验证方式">
                        <el-radio-group v-model="form.verificationMethod">
                            <el-radio label="captcha">验证码</el-radio>
                            <el-radio label="question">问答验证</el-radio>
                            <el-radio label="both">两者都需要</el-radio>
                            <el-radio label="channel">关注频道</el-radio>
                            <el-radio label="captcha_channel">验证码+关注频道</el-radio>
                            <el-radio label="question_channel">问答+关注频道</el-radio>
                            <el-radio label="both_channel">全部验证方式</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="验证时间限制(分钟)">
                        <el-input-number v-model="form.timeLimit" :min="1" :max="60" :step="1"
                            @change="handleTimeLimitChange" />
                    </el-form-item>

                    <template v-if="form.verificationMethod.includes('question')">
                        <el-form-item label="验证问题">
                            <el-input v-model="form.question" placeholder="请输入验证问题" />
                        </el-form-item>

                        <el-form-item label="可接受的答案">
                            <div class="answer-inputs">
                                <div v-for="(answer, index) in form.answers" :key="index" class="answer-item">
                                    <el-input v-model="form.answers[index]" placeholder="请输入答案" />
                                    <el-button type="danger" :icon="Delete" circle @click="removeAnswer(index)" />
                                </div>
                                <el-button type="primary" @click="addAnswer">添加答案</el-button>
                            </div>
                            <div class="form-tip">多个答案中匹配任意一个即视为验证通过</div>
                        </el-form-item>
                    </template>

                    <template v-if="form.verificationMethod.includes('channel')">
                        <el-form-item label="必须关注的频道">
                            <div class="channel-inputs">
                                <div v-for="(channel, index) in form.requiredChannels" :key="index"
                                    class="channel-item">
                                    <el-select v-model="channel.type" style="width: 120px;">
                                        <el-option label="频道" value="channel" />
                                        <el-option label="群组" value="group" />
                                    </el-select>
                                    <el-input v-model="channel.chatId" placeholder="频道ID/用户名(@channel)或频道链接"
                                        style="width: 250px; margin: 0 10px;" />
                                    <el-input v-model="channel.title" placeholder="频道/群组名称(显示用)"
                                        style="width: 150px; margin-right: 10px;" />
                                    <el-input v-model="channel.inviteLink" placeholder="邀请链接(用户点击加入用)"
                                        style="width: 250px; margin-right: 10px;" />
                                    <el-button type="danger" :icon="Delete" circle @click="removeChannel(index)" />
                                </div>
                                <el-button type="primary" @click="addChannel">添加频道/群组</el-button>
                            </div>
                            <div class="form-tip">用户必须关注所有指定的频道/群组才能通过验证</div>
                            <div class="form-tip-warning">注意：chatId填写格式有三种：1) 数字ID格式如-1001234567890 2) 用户名格式如@channel 3)
                                链接格式如https://t.me/channel</div>
                            <div class="form-tip-warning">确保机器人已被设为频道或群组的管理员，否则无法验证用户关注状态</div>
                        </el-form-item>
                    </template>

                    <el-form-item label="验证失败动作">
                        <el-radio-group v-model="form.actionOnFailure">
                            <el-radio label="kick">踢出群组</el-radio>
                            <el-radio label="ban">暂时封禁</el-radio>
                            <el-radio label="restrict">仅限制权限</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item v-if="form.actionOnFailure === 'ban'" label="封禁时长(小时)">
                        <el-input-number v-model="form.banDurationHours" :min="1" :max="168" :step="1"
                            @change="handleBanDurationChange" />
                    </el-form-item>

                    <el-form-item label="欢迎消息">
                        <el-input v-model="form.welcomeMessage" type="textarea" :rows="3"
                            placeholder="验证通过后发送的欢迎消息，可使用{user}代表用户" />
                        <div class="form-tip">可使用{user}代表用户名，如：欢迎{user}加入本群！</div>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="saveSettings" :loading="saving">保存设置</el-button>
                    </el-form-item>
                </el-form>
            </el-card>
        </div>

        <div v-if="selectedGroupId" class="logs-section">
            <el-card class="settings-card">
                <template #header>
                    <div class="card-header">
                        <span>验证记录</span>
                        <div class="filter-controls">
                            <el-select v-model="logFilter.status" placeholder="筛选状态" @change="fetchLogs"
                                style="width: 120px;">
                                <el-option label="全部" value="all" />
                                <el-option label="待验证" value="pending" />
                                <el-option label="通过" value="passed" />
                                <el-option label="失败" value="failed" />
                                <el-option label="超时" value="timeout" />
                            </el-select>
                            <el-button type="primary" :icon="Refresh" circle @click="fetchLogs"
                                :loading="loadingLogs"></el-button>
                        </div>
                    </div>
                </template>

                <el-table v-loading="loadingLogs" :data="logs" style="width: 100%" border>
                    <el-table-column prop="userName" label="用户名" min-width="100" />
                    <el-table-column prop="userId" label="用户ID" min-width="100" />
                    <el-table-column label="验证方式" min-width="120">
                        <template #default="scope">
                            <el-tag v-if="scope.row.method === 'captcha'" type="primary">验证码</el-tag>
                            <el-tag v-if="scope.row.method === 'question'" type="success">问答验证</el-tag>
                            <el-tag v-if="scope.row.method === 'both'" type="warning">双重验证</el-tag>
                            <el-tag v-if="scope.row.method === 'channel'" type="info">频道验证</el-tag>
                            <el-tag v-if="scope.row.method === 'captcha_channel'" type="primary">验证码+频道</el-tag>
                            <el-tag v-if="scope.row.method === 'question_channel'" type="success">问答+频道</el-tag>
                            <el-tag v-if="scope.row.method === 'both_channel'" type="warning">全部验证</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="状态" min-width="100">
                        <template #default="scope">
                            <el-tag v-if="scope.row.status === 'pending'" type="info">待验证</el-tag>
                            <el-tag v-if="scope.row.status === 'passed'" type="success">通过</el-tag>
                            <el-tag v-if="scope.row.status === 'failed'" type="danger">失败</el-tag>
                            <el-tag v-if="scope.row.status === 'timeout'" type="warning">超时</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="开始时间" min-width="160">
                        <template #default="scope">
                            {{ formatDate(scope.row.startTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column label="完成时间" min-width="160">
                        <template #default="scope">
                            {{ scope.row.endTime ? formatDate(scope.row.endTime) : '-' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="执行动作" min-width="100">
                        <template #default="scope">
                            <span v-if="scope.row.actionTaken === 'none'">无</span>
                            <el-tag v-if="scope.row.actionTaken === 'kick'" type="danger">踢出</el-tag>
                            <el-tag v-if="scope.row.actionTaken === 'ban'" type="danger">封禁</el-tag>
                            <el-tag v-if="scope.row.actionTaken === 'restrict'" type="warning">限制</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100" fixed="right">
                        <template #default="scope">
                            <el-button type="text" size="small" @click="handleDetail(scope.row)">
                                详情
                            </el-button>
                            <el-button type="text" size="small" @click="handleDelete(scope.row)">
                                删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="pagination">
                    <el-pagination v-if="logPagination.total > 0" background layout="prev, pager, next"
                        :total="logPagination.total" :page-size="logPagination.limit" :current-page="logPagination.page"
                        @current-change="handlePageChange" />
                </div>
            </el-card>
        </div>

        <!-- 验证详情对话框 -->
        <el-dialog title="验证详情" v-model="detailDialogVisible" width="500px">
            <div v-if="currentDetail" class="verification-detail">
                <div class="detail-item">
                    <span class="label">用户名：</span>
                    <span>{{ currentDetail.userName || currentDetail.userId }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">验证方式：</span>
                    <span>{{ methodMap[currentDetail.method] }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">验证状态：</span>
                    <span>{{ statusMap[currentDetail.status] }}</span>
                </div>
                <div v-if="currentDetail.captchaCode" class="detail-item">
                    <span class="label">验证码：</span>
                    <span>{{ currentDetail.captchaCode }}</span>
                </div>
                <div v-if="currentDetail.userCaptcha" class="detail-item">
                    <span class="label">用户输入验证码：</span>
                    <span>{{ currentDetail.userCaptcha }}</span>
                </div>
                <div v-if="currentDetail.question" class="detail-item">
                    <span class="label">问题：</span>
                    <span>{{ currentDetail.question }}</span>
                </div>
                <div v-if="currentDetail.userAnswer" class="detail-item">
                    <span class="label">用户回答：</span>
                    <span>{{ currentDetail.userAnswer }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">开始时间：</span>
                    <span>{{ formatDate(currentDetail.startTime) }}</span>
                </div>
                <div v-if="currentDetail.endTime" class="detail-item">
                    <span class="label">完成时间：</span>
                    <span>{{ formatDate(currentDetail.endTime) }}</span>
                </div>
                <div class="detail-item">
                    <span class="label">执行动作：</span>
                    <span>{{ actionMap[currentDetail.actionTaken] }}</span>
                </div>
                <div v-if="currentDetail.channelVerified !== undefined" class="detail-item">
                    <span class="label">频道验证：</span>
                    <span>{{ currentDetail.channelVerified ? '已通过' : '未通过' }}</span>
                </div>
                <div v-if="currentDetail.verifiedChannels && currentDetail.verifiedChannels.length > 0"
                    class="detail-item">
                    <span class="label">已验证频道：</span>
                    <div>
                        <div v-for="(chatId, index) in currentDetail.verifiedChannels" :key="index">
                            {{ chatId }}
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Refresh } from '@element-plus/icons-vue';
import { getGroups } from '../../../api/group';
import { getVerificationSettings, updateVerificationSettings, getVerificationLogs, deleteVerificationLog } from '../../../api/verification';

export default {
    name: 'VerificationSettings',
    setup() {
        // 数据
        const loading = ref(false);
        const saving = ref(false);
        const loadingLogs = ref(false);
        const groupList = ref([]);
        const selectedGroupId = ref('');
        const detailDialogVisible = ref(false);
        const currentDetail = ref(null);

        // 表单数据
        const form = reactive({
            enabled: false,
            verificationMethod: 'captcha',
            timeLimit: 5 * 60, // 默认5分钟，存储为秒
            question: '',
            answers: [''],
            actionOnFailure: 'kick',
            banDurationHours: 24, // UI显示用，小时
            welcomeMessage: '欢迎{user}加入本群！',
            requiredChannels: [{ type: 'channel', chatId: '', title: '', inviteLink: '' }]
        });

        // 日志数据
        const logs = ref([]);
        const logPagination = reactive({
            total: 0,
            page: 1,
            limit: 20,
            pages: 0
        });
        const logFilter = reactive({
            status: 'all'
        });

        // 状态映射
        const methodMap = {
            'captcha': '验证码',
            'question': '问答验证',
            'both': '双重验证',
            'channel': '频道验证',
            'captcha_channel': '验证码+频道验证',
            'question_channel': '问答+频道验证',
            'both_channel': '全部验证方式'
        };

        const statusMap = {
            'pending': '待验证',
            'passed': '通过',
            'failed': '失败',
            'timeout': '超时'
        };

        const actionMap = {
            'none': '无',
            'kick': '踢出',
            'ban': '封禁',
            'restrict': '限制'
        };

        // 初始化
        onMounted(async () => {
            await fetchGroups();
        });

        // 获取群组列表
        const fetchGroups = async () => {
            loading.value = true;
            try {
                const res = await getGroups();
                if (res.data.success) {
                    groupList.value = res.data.data;
                } else {
                    ElMessage.error(res.data.message || '获取群组失败');
                }
            } catch (error) {
                console.error('获取群组失败:', error);
                ElMessage.error('获取群组失败');
            } finally {
                loading.value = false;
            }
        };

        // 选择群组时加载设置
        const handleGroupChange = async (groupId) => {
            if (!groupId) return;

            loading.value = true;
            try {
                const res = await getVerificationSettings(groupId);
                if (res.data.success) {
                    const settings = res.data.data;

                    // 转换数据到表单
                    form.enabled = settings.enabled;
                    form.verificationMethod = settings.verificationMethod;
                    form.timeLimit = Math.round(settings.timeLimit / 60); // 从秒转为分钟显示
                    form.question = settings.question || '';
                    form.answers = settings.answers && settings.answers.length > 0 ? settings.answers : [''];
                    form.actionOnFailure = settings.actionOnFailure;
                    form.banDurationHours = Math.round(settings.banDuration / 3600);
                    form.welcomeMessage = settings.welcomeMessage;
                    form.requiredChannels = settings.requiredChannels && settings.requiredChannels.length > 0
                        ? settings.requiredChannels
                        : [{ type: 'channel', chatId: '', title: '', inviteLink: '' }];
                } else {
                    ElMessage.error(res.data.message || '获取设置失败');
                }
            } catch (error) {
                console.error('获取设置失败:', error);
                ElMessage.error('获取设置失败');
            } finally {
                loading.value = false;
            }

            // 加载验证记录
            fetchLogs();
        };

        // 保存设置
        const saveSettings = async () => {
            if (!selectedGroupId.value) {
                ElMessage.warning('请先选择群组');
                return;
            }

            // 验证问答设置
            if (form.verificationMethod.includes('question')) {
                if (!form.question) {
                    ElMessage.warning('请输入验证问题');
                    return;
                }

                if (!form.answers.some(a => a.trim())) {
                    ElMessage.warning('请至少添加一个有效答案');
                    return;
                }
            }

            // 验证频道设置
            if (form.verificationMethod.includes('channel')) {
                if (!form.requiredChannels.some(c => c.chatId.trim())) {
                    ElMessage.warning('请至少添加一个频道或群组');
                    return;
                }
            }

            saving.value = true;
            try {
                // 转换小时到秒
                if (form.actionOnFailure === 'ban') {
                    form.banDuration = form.banDurationHours * 3600;
                }

                // 过滤空答案
                const filteredAnswers = form.answers.filter(a => a.trim());

                // 过滤空频道
                const filteredChannels = form.requiredChannels.filter(c => c.chatId.trim());

                const settingsData = {
                    enabled: form.enabled,
                    verificationMethod: form.verificationMethod,
                    timeLimit: form.timeLimit * 60, // 将分钟转换为秒再发送给后端
                    question: form.question,
                    answers: filteredAnswers,
                    actionOnFailure: form.actionOnFailure,
                    banDuration: form.banDuration,
                    welcomeMessage: form.welcomeMessage,
                    requiredChannels: filteredChannels
                };

                const res = await updateVerificationSettings(selectedGroupId.value, settingsData);
                if (res.data.success) {
                    ElMessage.success('设置已保存');
                } else {
                    ElMessage.error(res.data.message || '保存设置失败');
                }
            } catch (error) {
                console.error('保存设置失败:', error);
                ElMessage.error('保存设置失败');
            } finally {
                saving.value = false;
            }
        };

        // 添加答案
        const addAnswer = () => {
            form.answers.push('');
        };

        // 删除答案
        const removeAnswer = (index) => {
            if (form.answers.length > 1) {
                form.answers.splice(index, 1);
            } else {
                form.answers = [''];
            }
        };

        // 处理时间限制变化
        const handleTimeLimitChange = (val) => {
            // 直接保存分钟值，不转换为秒，因为后端会在接收到后自动转换
            form.timeLimit = val;
        };

        // 处理封禁时长变化
        const handleBanDurationChange = (val) => {
            form.banDurationHours = val;
            form.banDuration = val * 3600; // 转换小时到秒
        };

        // 获取验证记录
        const fetchLogs = async () => {
            if (!selectedGroupId.value) return;

            loadingLogs.value = true;
            try {
                const params = {
                    page: logPagination.page,
                    limit: logPagination.limit,
                    status: logFilter.status === 'all' ? '' : logFilter.status
                };

                const res = await getVerificationLogs(selectedGroupId.value, params);
                if (res.data.success) {
                    logs.value = res.data.data;
                    logPagination.total = res.data.pagination.total;
                    logPagination.page = res.data.pagination.page;
                    logPagination.limit = res.data.pagination.limit;
                    logPagination.pages = res.data.pagination.pages;
                } else {
                    ElMessage.error(res.data.message || '获取验证记录失败');
                }
            } catch (error) {
                console.error('获取验证记录失败:', error);
                ElMessage.error('获取验证记录失败');
            } finally {
                loadingLogs.value = false;
            }
        };

        // 处理分页变化
        const handlePageChange = (page) => {
            logPagination.page = page;
            fetchLogs();
        };

        // 查看详情
        const handleDetail = (row) => {
            currentDetail.value = row;
            detailDialogVisible.value = true;
        };

        // 删除记录
        const handleDelete = (row) => {
            ElMessageBox.confirm('确定要删除这条验证记录吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                try {
                    const res = await deleteVerificationLog(row._id);
                    if (res.data.success) {
                        ElMessage.success('删除成功');
                        fetchLogs();
                    } else {
                        ElMessage.error(res.data.message || '删除失败');
                    }
                } catch (error) {
                    console.error('删除记录失败:', error);
                    ElMessage.error('删除记录失败');
                }
            }).catch(() => { });
        };

        // 格式化日期
        const formatDate = (dateString) => {
            if (!dateString) return '-';
            const date = new Date(dateString);
            return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
        };

        // 添加频道
        const addChannel = () => {
            form.requiredChannels.push({ type: 'channel', chatId: '', title: '', inviteLink: '' });
        };

        // 删除频道
        const removeChannel = (index) => {
            if (form.requiredChannels.length > 1) {
                form.requiredChannels.splice(index, 1);
            } else {
                form.requiredChannels = [{ type: 'channel', chatId: '', title: '', inviteLink: '' }];
            }
        };

        return {
            loading,
            saving,
            loadingLogs,
            groupList,
            selectedGroupId,
            form,
            logs,
            logPagination,
            logFilter,
            detailDialogVisible,
            currentDetail,
            methodMap,
            statusMap,
            actionMap,
            handleGroupChange,
            saveSettings,
            addAnswer,
            removeAnswer,
            handleTimeLimitChange,
            handleBanDurationChange,
            fetchLogs,
            handlePageChange,
            handleDetail,
            handleDelete,
            formatDate,
            Delete,
            Refresh,
            addChannel,
            removeChannel
        };
    }
};
</script>

<style scoped>
.verification-container {
    padding: 20px;
}

.settings-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.group-select {
    padding: 10px 0;
}

.group-selector {
    width: 300px;
}

.form-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 5px;
}

.answer-inputs {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.answer-item {
    display: flex;
    align-items: center;
    gap: 10px;
}

.filter-controls {
    display: flex;
    align-items: center;
    gap: 10px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}

.verification-detail {
    padding: 10px;
}

.detail-item {
    margin-bottom: 10px;
    display: flex;
}

.detail-item .label {
    font-weight: bold;
    width: 150px;
}

.channel-inputs {
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.channel-item {
    display: flex;
    align-items: center;
    gap: 10px;
}

.form-tip-warning {
    font-size: 12px;
    color: #E6A23C;
    margin-top: 5px;
}
</style>